// src/store/userStore.js
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
    state: () => ({
        isLoggedIn: false,
        userData: null
    }),

    actions: {
        // 登录方法
        login(userData) {
            this.isLoggedIn = true;
            this.userData = userData;

            // 保存用户数据到 localStorage
            localStorage.setItem('userData', JSON.stringify(userData));
            localStorage.setItem('isLoggedIn', 'true');
        },

        // 登出方法
        logout() {
            this.isLoggedIn = false;
            this.userData = null;

            // 清除 localStorage 中的用户数据
            localStorage.removeItem('userData');
            localStorage.removeItem('isLoggedIn');
        },

        // 初始化方法，用于在应用启动时从 localStorage 中加载数据
        initialize() {
            const storedUserData = localStorage.getItem('userData');
            const storedIsLoggedIn = localStorage.getItem('isLoggedIn');

            if (storedIsLoggedIn === 'true' && storedUserData) {
                this.isLoggedIn = true;
                this.userData = JSON.parse(storedUserData);
            }
        }
    }
});
